package cmc

import (
	"context"
	model "service/model/crm_base"
	"time"

	gpb "gitee.com/cloudapex/protos/crm_base/pb"
	"gitee.com/cloudapex/ulern/htp"
	"github.com/gin-gonic/gin"
)

/*
 * 描述: 客户出格登记
 * 路由: /cmc/wayOut
 * 方法: POST
 *********************************************************************/
type WayOut struct {
	BId    int64  `form:"bId" json:"bId" binding:"required"`       // 机会Id
	CsId   int64  `form:"csId" json:"csId" binding:"required"`     // 客户Id
	UserId int64  `form:"userId" json:"userId" binding:"required"` // 坐席Id
	Reason string `form:"reason" json:"reason" binding:"required"` // 原因
}

func (this *WayOut) Handle(c *gin.Context, ctx context.Context) htp.Response {
	//user := mod.CurrUser(c)

	// 正在审核中
	rsp, err := model.Base.SelectPool(ctx, &gpb.BasePoolReq{
		BasePool: &gpb.BasePool{
			BaseBase: &gpb.BaseBase{},
			BaseProject: &gpb.BaseProject{
				Id:    uint64(this.CsId),
				Logic: 3, // 静默库
			},
			BaseProTg: &gpb.BaseProTg{},
		},
	})
	if err != nil {
		return htp.RespModelErr("_s", err)
	}
	if rsp.BasePool != nil {
		return htp.RespErr(1, "此客户Id正在审核中", nil)
	}

	// 添加登记(进入静默库)
	//_, err = model.Base.SetPoolLogic(ctx, &gpb.PoolLogicReq{Id: uint64(this.CsId), Logic: int64(model.EBaseL_Silent)})
	_, err = model.Base.EditPool(ctx, &gpb.BasePoolReq{
		BasePool: &gpb.BasePool{
			BaseBase: &gpb.BaseBase{Id: uint64(this.BId)},
			BaseProject: &gpb.BaseProject{
				Id:      uint64(this.CsId),
				ShareAt: time.Now().Unix(),
				Nodes:   this.Reason,
				Logic:   int64(model.EBaseL_Silent),
			},
			BaseProTg: &gpb.BaseProTg{},
		},
	})
	if err != nil {
		return htp.RespModelErr("_p", err)
	}

	// 工作池的logic状态
	_, err = model.Work.SetWorkLogic(ctx, &gpb.WorkLogicReq{Id: uint64(this.CsId), Logic: int64(model.EBaseL_Silent)})
	if err != nil {
		return htp.RespModelErr("_w", err)
	}

	// 添加出格记录
	_, err = model.PoolOutNode.PoolOutNodeAdd(ctx, &gpb.PoolOutNode{
		BId:  uint64(this.BId),
		BpId: uint64(this.CsId),
		Node: this.Reason,
		UId:  this.UserId,
		//OperId: user.UId,
		At: time.Now().Unix(),
	})
	if err != nil {
		return htp.RespModelErr("_n", err)
	}

	return htp.RespOK("", nil)
}
